package  common.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;

import util.DebugUtil;



/**
 * Connection代理
 */
public class ConnectionProxy  extends ObjectProxy {
    
	private boolean closeFlag = false;//connection关闭标记
	private boolean autoCommitFlag = false;//事务自动提交标记
	
	public ConnectionProxy(Object Connection) {
		super(Connection); 	
		proxyMethod = new String[]{"setAutoCommit","commit","close","rollback"};	
	}
	
	protected Class<Connection> getInterfaceClass() {
		return Connection.class;
	}
	
	public void setAutoCommitFlag(boolean autoCommitFlag) {
		this.autoCommitFlag = autoCommitFlag;
	}

	public void setCloseFlag(boolean closeFlag) {
		this.closeFlag = closeFlag;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		String methodName = method.getName();//方法名
		DebugUtil.print(this.getClass().getName() + ":执行Connection方法[" + methodName + "]");
		
		//调用相应的方法
		Object obj = null;
		try {
			if(this.isProxyMethod(methodName)) {
				if (("close".equals(methodName))) {//关闭
					if (this.closeFlag) {
						obj = method.invoke(this.realObj, args);
						DebugUtil.print(this.getClass().getName() + ":Connection.close");
					} else {
						DebugUtil.print(this.getClass().getName() + ":Connection.close不处理");
					}
				} else if ("commit".equals(methodName)) { //开始事务
					if (this.autoCommitFlag) {
						obj = method.invoke(this.realObj, args);
						DebugUtil.print(this.getClass().getName() + "Connection.commit");
					} else { 
						DebugUtil.print(this.getClass().getName() + "Connection.commit不处理");
					}
				} else { 
					obj = method.invoke(this.realObj, args);
				}
			} else { 
				obj = method.invoke(this.realObj, args);
			}
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
		return obj;
	}

}
